//
//  YWKeepWatchAndInspectRecordViewController.m
//  maintain
//
//  Created by Kyo on 16/7/28.
//  Copyright © 2016年 ewin. All rights reserved.
//

#import "YWKeepWatchAndInspectRecordViewController.h"
#import "MJRefresh.h"
#import "UIColor+CustomColors.h"
#import "NSDate+Additions.h"
#import "YWMacro.h"
#import "YWCommonTool.h"
#import "UIImageView+WebCache.h"
#import "YWBuildingManager.h"
#import "YWBuilding.h"
#import "YWEquipmentDetailCell.h"
#import "YWInspectionEquipmentRecord.h"
#import "YWPatrolPointRecord.h"
#import "YWMissionManager.h"
#import "YWKeepWatchMissionManager.h"
#import "YWInspectionMissionManager.h"
#import "YWKeepWatchLocationRecordDetailTableViewController.h"
#import "YWInspecLocationRecordDetailTableViewController.h"

@interface YWKeepWatchAndInspectRecordViewController ()<UITableViewDataSource, UITableViewDelegate> {
//    NSTimeInterval keepWatchRecordMinCompleteTime;
//    NSTimeInterval inspectionListRecordMinCompleteTime;
}
@property (nonatomic, strong) UIView* headView;
@property (nonatomic, strong) UITableView* tableView;
@property (nonatomic, strong) NSMutableArray* recordArray;

@property (nonatomic, strong) UIImageView* buildingImageView;
@property (nonatomic, strong) UILabel *buildingLabel;
@property (nonatomic, strong) UIImageView *locationIV;
@property (nonatomic, strong) UILabel *locationLabel;

@property (nonatomic, assign) NSInteger page;
@end

@implementation YWKeepWatchAndInspectRecordViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"巡查巡更详情";
    self.view.backgroundColor = [UIColor customBackgroudColor];
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    self.page = 1;
    self.tableView.backgroundColor = [UIColor customBackgroudColor];
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshTop)];
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(refreshFootor)];
    self.tableView.mj_footer.automaticallyHidden = YES;
    // 马上进入刷新状态
    [self.tableView.mj_header beginRefreshing];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (NSMutableArray *)recordArray{
    if (!_recordArray) {
        NSMutableArray* recordArray = [NSMutableArray array];
        [recordArray addObjectsFromArray:[[YWMissionManager shareManager] keepWatchAndInspectRecordsWithLocationId:self.locatonId andPage:self.page]];
        
        __block NSDate* lastDate = nil;
        [recordArray enumerateObjectsUsingBlock:^(id _Nonnull record, NSUInteger idx, BOOL* _Nonnull stop) {
            if ([record isKindOfClass:[YWInspectionEquipmentRecord class]]) {
                YWInspectionEquipmentRecord* equipmentRecord = (YWInspectionEquipmentRecord*)record;
                equipmentRecord.pictures = [[YWKeepWatchMissionManager shareManager] recordPictureWithRecordId:equipmentRecord.equipmentRecordId recordType:YWPictureRecordTypeInspectionMission];
                NSDate* completeDate = [NSDate dateWithTimeIntervalSince1970:equipmentRecord.executeTime / 1000];
                if (completeDate.year == lastDate.year && completeDate.month == lastDate.month && completeDate.day == lastDate.day) {
                    equipmentRecord.dayMonthString = nil;
                }
                else {
                    if (completeDate.isToday) {
                        equipmentRecord.dayMonthString = @"今天";
                    }
                }
                lastDate = completeDate;
            }
            else {
                YWPatrolPointRecord* patrolPointRecord = (YWPatrolPointRecord*)record;
                patrolPointRecord.pictures = [[YWKeepWatchMissionManager shareManager] recordPictureWithRecordId:patrolPointRecord.patrolpointRecordId recordType:YWPictureRecordTypePatrol];
                NSDate* completeDate = [NSDate dateWithTimeIntervalSince1970:patrolPointRecord.patrolTime / 1000];
                if (completeDate.year == lastDate.year && completeDate.month == lastDate.month && completeDate.day == lastDate.day) {
                    patrolPointRecord.dayMonthString = nil;
                }
                else {
                    if (completeDate.isToday) {
                        patrolPointRecord.dayMonthString = @"今天";
                    }
                }
                lastDate = completeDate;
            }
            
        }];
        _recordArray = recordArray;
        //[self getMinCompleteTime];
    }
    return _recordArray;
}
- (void)refreshTop
{
    self.page = 1;
    [self.tableView.mj_footer resetNoMoreData];
    [self requestData:YWTableViewFreshTypeDown];
}

- (void)refreshFootor
{
    [self requestData:YWTableViewFreshTypeUp];
}

- (void)requestData:(YWTableViewFreshType)refreshType{
    YWWeakSelf(weakSelf);
    dispatch_group_t group = dispatch_group_create();
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        if (refreshType == YWTableViewFreshTypeUp) {
            self.page++;
        }
        dispatch_group_enter(group);
        [[YWKeepWatchMissionManager shareManager] requestPatrolPointRecord:self.locatonId page:self.page pageSize:10 complete:^(BOOL success) {
            dispatch_group_leave(group);
        }];
        
        dispatch_group_enter(group);
        [[YWInspectionMissionManager shareManager] requestInspectionLocationRecord:self.locatonId page:self.page pageSize:10 complete:^(BOOL success) {
            dispatch_group_leave(group);
        }];
        
        dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
        dispatch_async(dispatch_get_main_queue(), ^{
            if (refreshType == YWTableViewFreshTypeDown) {
                [weakSelf.tableView.mj_header endRefreshing];
            }
            else {
                [weakSelf.tableView.mj_footer endRefreshing];
            }
            weakSelf.recordArray = nil;
            [weakSelf.tableView reloadData];
        });
    });
}


//- (void)getMinCompleteTime
//{
//    keepWatchRecordMinCompleteTime = 0;
//    inspectionListRecordMinCompleteTime = 0;
//    for (id object in _recordArray) {
//        if ([object isKindOfClass:[YWInspectionEquipmentRecord class]]) {
//            YWInspectionEquipmentRecord* equipmentRecord = (YWInspectionEquipmentRecord*)object;
//            inspectionListRecordMinCompleteTime = inspectionListRecordMinCompleteTime ? MIN(inspectionListRecordMinCompleteTime, equipmentRecord.executeTime) : equipmentRecord.executeTime;
//        }
//        else if ([object isKindOfClass:[YWPatrolPointRecord class]]) {
//            YWPatrolPointRecord* record = (YWPatrolPointRecord*)object;
//            keepWatchRecordMinCompleteTime = keepWatchRecordMinCompleteTime ? MIN(keepWatchRecordMinCompleteTime, record.patrolTime) : record.patrolTime;
//        }
//    }
//}
#pragma mark - UITableViewDataSource
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 19;
}
- (CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath
{
    return 54;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView*)tableView
{
    return self.recordArray.count;
}

- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath
{
    YWEquipmentDetailCell* cell = [YWEquipmentDetailCell cellWithTableView:tableView];
    id record = self.recordArray[indexPath.section];
    if ([record isKindOfClass:[YWInspectionEquipmentRecord class]]) {
        YWInspectionEquipmentRecord* equipmentRecord = (YWInspectionEquipmentRecord*)record;
        cell.inspectionEquipmentRecord = equipmentRecord;
    }
    else {
        YWPatrolPointRecord* patrolPointRecord = (YWPatrolPointRecord*)record;
        cell.patrolPointRecord = patrolPointRecord;
    }
    
    return cell;
}
- (void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath
{
    id record = self.recordArray[indexPath.section];
    if ([record isKindOfClass:[YWInspectionEquipmentRecord class]]) {
        YWInspectionEquipmentRecord* equipmentRecord = (YWInspectionEquipmentRecord*)record;
        YWInspecLocationRecordDetailTableViewController *locationDetailVc = [[YWInspecLocationRecordDetailTableViewController alloc] init];
        locationDetailVc.inspectionEquipmentRecord = equipmentRecord;
        [self.navigationController pushViewController:locationDetailVc animated:YES];
    }
    else {
        YWPatrolPointRecord* patrolPointRecord = (YWPatrolPointRecord*)record;
        YWKeepWatchLocationRecordDetailTableViewController* detailVC = [[YWKeepWatchLocationRecordDetailTableViewController alloc] init];
        detailVC.patrolPointRecord = patrolPointRecord;
        [self.navigationController pushViewController:detailVC animated:YES];
    }
}

- (UITableView*)tableView
{
    if (!_tableView) {
        UITableView* tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64) style:UITableViewStyleGrouped];
        tableView.backgroundColor = [UIColor customBackgroudColor];
        tableView.sectionFooterHeight = 1.0;
        tableView.delegate = self;
        tableView.dataSource = self;
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        tableView.tableHeaderView = self.headView;
        [self.view addSubview:tableView];
        _tableView = tableView;
    }
    return _tableView;
}
- (UIView*)headView
{
    if (!_headView) {
        UIView* headView = [[UIView alloc] init];
        headView.backgroundColor = [UIColor whiteColor];
        NSInteger locationId = self.locatonId;
        YWBuilding* building = [[YWBuildingManager shareManager] buildingWithLocationId:locationId];
        NSString* downloadUrl = [YWCommonTool pictureDownloadUrl:building.surfacePicture];
        [self.buildingImageView sd_setImageWithURL:[NSURL URLWithString:downloadUrl] placeholderImage:[UIImage imageNamed:@"placeholder_buliding"]];
        CGFloat imageSize = kLabelH*2;
        [self.buildingImageView setFrame:CGRectMake(kMarginW, kGapH, imageSize, imageSize)];
        
        self.buildingLabel.text = building.buildingName.length>0?building.buildingName:@"未知楼盘";
        CGFloat buildingW = SCREEN_WIDTH-kMarginW*3-imageSize;
        CGFloat buildingH = [YWCommonTool getHeightOfLabel:self.buildingLabel.text andWidth:buildingW andFont:self.buildingLabel.font andMinHeight:kLabelH];
        [self.buildingLabel setFrame:CGRectMake(CGRectGetMaxX(self.buildingImageView.frame)+kMarginW, kGapH, buildingW, buildingH)];
        
        [self.locationIV setFrame:CGRectMake(CGRectGetMaxX(self.buildingImageView.frame)+kMarginW, CGRectGetMaxY(self.buildingLabel.frame) + 2.5, 17, 17)];
        
        NSString* position = [[YWBuildingManager shareManager] areaLocationNobuildingWithId:locationId];
        NSString *locationStr = position.length ? position : @"位置未填写";
        self.locationLabel.text = locationStr;
        CGFloat locationW = SCREEN_WIDTH - 17 - 3 - kMarginW*3-imageSize;
        CGFloat locationH = [YWCommonTool getHeightOfLabel:self.locationLabel.text andWidth:locationW andFont:self.locationLabel.font andMinHeight:kLabelH];
        [self.locationLabel setFrame:CGRectMake(CGRectGetMaxX(self.locationIV.frame) + 3, CGRectGetMaxY(self.buildingLabel.frame), locationW, locationH)];
        
        [headView addSubview:self.buildingImageView];
        [headView addSubview:self.buildingLabel];
        [headView addSubview:self.locationIV];
        [headView addSubview:self.locationLabel];
        [headView setFrame:CGRectMake(0, 0, SCREEN_WIDTH, kGapH*2 + buildingH + locationH)];
        
        _headView = headView;
    }
    return _headView;
}

- (UIImageView*)buildingImageView
{
    if (!_buildingImageView) {
        UIImageView* buildingImageView = [[UIImageView alloc] init];
        buildingImageView.clipsToBounds = YES;
        buildingImageView.layer.cornerRadius = 22.0;
        _buildingImageView = buildingImageView;
        [self.headView addSubview:_buildingImageView];
    }
    return _buildingImageView;
}
- (UILabel*)buildingLabel
{
    if (!_buildingLabel) {
        UILabel* buildingLabel = [[UILabel alloc] init];
        buildingLabel.font = [UIFont boldSystemFontOfSize:16];
        buildingLabel.numberOfLines = 0;
        _buildingLabel = buildingLabel;
        [self.headView addSubview:_buildingLabel];
    }
    return _buildingLabel;
}

- (UIImageView*)locationIV
{
    if (!_locationIV) {
        UIImageView* locationImageV = [[UIImageView alloc] init];
        locationImageV.image = [UIImage imageNamed:@"common_location"];
        _locationIV = locationImageV;
        [self.headView addSubview:_locationIV];
    }
    return _locationIV;
}

- (UILabel*)locationLabel
{
    if (!_locationLabel) {
        UILabel* locationLabel = [[UILabel alloc] init];
        locationLabel.font = KSmallContentFont;
        locationLabel.textColor = [UIColor customTextGrayColor];
        locationLabel.numberOfLines = 0;
        _locationLabel = locationLabel;
        [self.headView addSubview:_locationLabel];
    }
    return _locationLabel;
}

@end
